package com.evildog.workspace.common.util;

import cn.hutool.core.util.ReflectUtil;
import feign.FeignException;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.nio.charset.StandardCharsets;

public class FeignUtil {

    private static final int MAX_BODY_BYTES_LENGTH = 400;

    /**
     * 获取feign中的异常信息
     */
    public static String getExceptionMessage(FeignException e){
        byte[] responseBody = (byte[]) ReflectUtil.getFieldValue(e, "responseBody");
        String feignErrorResponse;
        if(responseBody != null){
            feignErrorResponse = new String(responseBody, StandardCharsets.UTF_8);
            if (feignErrorResponse.length() > MAX_BODY_BYTES_LENGTH) {
                feignErrorResponse = feignErrorResponse.substring(0, 400);
            }
        }else{
            feignErrorResponse = ExceptionUtils.getMessage(e);
        }

        return feignErrorResponse;
    }
}
